package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;

public class PhotoUtil {
	
	public static Bitmap getBitmapFromString(String str_path,boolean isResize){
		File file = new File(str_path);
		return getBitmapFromFile(file,isResize);
	}
	
	public static Bitmap getBitmapFromFile(File imgFile,boolean isResize){
		float rot = 0;
		ExifInterface exif;
		try {
			exif = new ExifInterface(imgFile.getAbsolutePath());
			String  ori  =exif.getAttribute(ExifInterface.TAG_ORIENTATION);
			
			System.out.println("ori:::::::"+ori);
			if("6".equals(ori)){
				rot =90;
			}else if("1".equals(ori)){
				rot=0;
			}else if("3".equals(ori)){
				rot=180;
			}else if("8".equals(ori)){
				rot=270;
			}else if("0".equals(ori)){
				//rot=90;
				rot=0;
			}else {
				rot=0;
			}
			//System.out.println("tag_ori:::::::"+);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Bitmap myBitmap =null;
		
		if(isResize){
			myBitmap = rotate(decodeFile(imgFile,240),rot);
		}else{
			myBitmap = rotate(BitmapFactory.decodeFile(imgFile.getAbsolutePath()),rot);
		}
		return myBitmap;
		
		
	}
	
	public static Bitmap rotate(Bitmap src, float degree) {
    	// create new matrix
    	Matrix matrix = new Matrix();
    	
    	
    	// setup rotation degree
    	matrix.postRotate(degree);

    	// return new bitmap rotated using matrix
    	
    	if(null == src ){
    		return null;
    	}
    	return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
    }
	
	private static Bitmap decodeFile(File f,int size ){
        try {
            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            
            //The new size we want to scale to
            final int REQUIRED_SIZE=size;

            //Find the correct scale value. It should be the power of 2.
            int scale=1;
            while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
                scale*=2;

            //Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }
	
	
	

}
